<template>
  <div v-if="!isPreview" class="vditor vditor-wrap" />
  <div v-else class="vditor-preview vditor-preview-wrap" />
</template>

<script>
import Vditor from 'vditor'
import 'vditor/dist/index.css'

export default {
  name: 'Vditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    height: {
      type: String || Number,
      default: '350px'
    },
    isPreview: {
      type: Boolean,
      default: false
    }
  },
  data: function() {
    return {
      contentEditor: '',
      toc: []
    }
  },
  mounted() {
    if (!this.isPreview) {
      this.$nextTick(() => {
        this.initEditor()
      })
    } else {
      this.preview()
    }
  },
  methods: {
    initEditor() {
      this.contentEditor = new Vditor('vditor', {
        height: this.height,
        toolbarConfig: {
          pin: true
        },
        cache: {
          enable: false
        },
        input: (md) => {
          this.$emit('input', md)
        },
        after: () => {
          this.contentEditor.setValue(this.value)
        }
      })
    },
    initOutline() {
      const headingElements = []
      Array.from(document.getElementById('preview').children).forEach((item) => {
        if (item.tagName.length === 2 && item.tagName !== 'HR' && item.tagName.indexOf('H') === 0) {
          headingElements.push(item)
        }
      })

      let toc = []
      window.addEventListener('scroll', () => {
        const scrollTop = window.scrollY
        toc = []
        headingElements.forEach((item) => {
          toc.push({
            id: item.id,
            offsetTop: item.offsetTop
          })
        })

        const currentElement = document.querySelector('.vditor-outline__item--current')
        for (let i = 0, iMax = toc.length; i < iMax; i++) {
          if (scrollTop < toc[i].offsetTop - 30) {
            if (currentElement) {
              currentElement.classList.remove('vditor-outline__item--current')
            }
            const index = i > 0 ? i - 1 : 0
            document.querySelector('div[data-id="' + toc[index].id + '"]').classList.add('vditor-outline__item--current')
            break
          }
        }
      })
    },
    preview() {
      // Vditor.md2html(this.value)
      Vditor.preview(document.getElementById('preview'),
        this.value, {
          speech: {
            enable: true
          },
          anchor: 1,
          after: () => {
            if (window.innerWidth <= 768) {
              return
            }
            // const outlineElement = document.getElementById('outline')
            // Vditor.outlineRender(document.getElementById('preview'), outlineElement)
            // if (outlineElement.innerText.trim() !== '') {
            //   outlineElement.style.display = 'block'
            //   this.initOutline()
            // }
            this.$emit('updated-toc', this.toc)
          },
          renderers: {
            renderHeading: (node, entering) => {
              const id = window.Lute.GetHeadingID(node)
              if (entering) {
                const header = {
                  level: node.__internal_object__.HeadingLevel,
                  text: node.Text(),
                  anchor: `h-${id}`
                }
                this.toc.push(header)
                return [
                  `<h${node.__internal_object__.HeadingLevel} id='h-${id}' class='heading'><span class='heading__prefix'></span><span class='heading__content'>`,
                  window.Lute.WalkContinue]
              } else {
                return [
                  `</span><span class='heading__suffix'></span><a id='vditorAnchor-${id}' class='v-vditor-anchor' data-anchor='h-${id}' href='javascript:;'></a></h${node.__internal_object__.HeadingLevel}>`,
                  window.Lute.WalkContinue]
              }
            }
          }
        }
      )
    }
  }
}
</script>
<style scoped lang="scss">

.vditor-wrap {
  max-height: 600px;
}
</style>
